#include "Level.h"
#include "Utils.h"
#include "Const.h"
#include "GameUtils.h"
#include "string.h"
#include "stdlib.h"

Level::Level()
{
	id = width = height = 0;
	data = 0;
}

Level::Level(int id, int width, int height, int* data)
{
	this->id = id;
	data = 0;
	SetSize(width, height);
	SetData(data);
}

void Level::SetID(int id)
{
	this->id = id;
}

void Level::SetSize(int width, int height)
{
	this->width = width;
	this->height = height;
	DELETE_SAFELY_ARRAY(data);
	data = new int[width*height];
}

void Level::SetData(int* data)
{
	for(int i = 0; i < width*height; i++)
	{
		this->data[i] = data[i];
	}
}

void Level::LoadLevelData(vector<Level*> *levels, char* islandName)
{
	char filePath[50];
	strcpy(filePath, ROOT_LEVEL_DIR);
	strcat(filePath,islandName);
	strcat(filePath, "/Levels.txt");

	vector<char*> lines;
	char* subStr;

	ReadTxtToLine(filePath, &lines);

	int i = 0;
	int s = lines.size();
	while(i < s)
	{
		char* line = lines[i];
		if(strcmp(line, "[Level]") == 0)	//begin a line
		{
			Level* level = new Level();

			i++;				//read id
			line = lines[i];
			level->SetID(atoi(line));

			int w, h;

			i++;
			line = lines[i];
			w = atoi(line);

			i++;
			line = lines[i];
			h = atoi(line);

			level->SetSize(w, h);

			// get data
			int *data = new int[w*h];
			int iteOfArray = 0;

			for(int j = 0; j < h; j++)		//with each row
			{
				i++;
				line = lines[i];
				for(int k = 0; k < w; k++)
				{
					if(k == 0)
						subStr = strtok(line, " ");
					else subStr = strtok(NULL, " ");
					
					int id = atoi(subStr);
					data[iteOfArray] = id;
					iteOfArray++;
				}
			}

			level->SetData(data);

			levels->push_back(level);
			i++;
		}
	}
}